#!/usr/bin/python3
# -*- coding: utf-8 -*-

import os
import re
from time import strftime, localtime
from reportlab.platypus import SimpleDocTemplate,Image, PageBreak
from reportlab.lib.pagesizes import A4, landscape, A3
import PIL.Image as PILImage
from PIL import ImageEnhance


image_tpye = [".jpg", ".jpeg", ".bmp", ".png"]

# A4 尺寸
A4_w, A4_h = landscape(A4)
A3_w, A3_h = landscape(A3)

# 检查是否是支持的图片
def isImage(file_path):
    if file_path and (os.path.splitext(file_path)[1] in image_tpye):
        return True
    else:
        return False


# 获取图片的尺寸
def getImageSize(imagePath):
        img = PILImage.open(imagePath)
        return img.size




# 图像增强
def image_enhance(pic_path):
    im = PILImage.open(pic_path)
    # 色彩增强
    enh_col = ImageEnhance.Color(im.convert('RGB'))
    im_enhance = enh_col.enhance(2.0)

    # 对比度增强
    enh_sha = ImageEnhance.Sharpness(im_enhance.convert('RGB'))
    im_enhance = enh_sha.enhance(2.0)

    # 覆盖原来的图像
    im_enhance.save(pic_path)

# 图像旋转
def image_roate(pic_path):
    im = PILImage.open(pic_path)

    # 逆时针旋转
    im_roate = im.transpose(PILImage.ROTATE_270)

    # 覆盖原来的图像
    im_roate.save(pic_path)



def image2PDF(ui, dir_path, save_name, doc_type):
    '''
    dir_path:  图片文件夹
    save_name: PDF保存名
    doc_type:  文档类型
    dele_image: 是否删除原来的图片
    '''
    pdf_pages = [] # 每一个元素是一张图路径
    pdf_list = []
    #save_path = dir_path + save_name   # pdf保存路径
    save_path = os.path.join(dir_path, save_name)
    #ui.printlog("pdf 保存路径: " + save_path)

    for parent, dirnames ,filenames in os.walk(dir_path):
        for file_name in filenames:
            file_path = os.path.join(parent, file_name)

            # 检查是否是图片
            if isImage(file_path):
                pdf_pages.append(file_path)
    # 排序函数
    sort_func = lambda path : int(re.findall('(\d+)\.png', path)[0])
    # 按照文件顺序排序
    pdf_pages = sorted(pdf_pages,key = sort_func)

    pdfBulid(ui, pdf_pages, save_path, doc_type, flag_enhance=True)

    # 第一次生成的有拉扯 bug?
    if doc_type == 'ppt':
        os.remove(save_path)
        ui.printlog("优化PDF质量...")
        pdfBulid(ui, pdf_pages, save_path, doc_type, flag_enhance=False)
        ui.printlog("质量优化完成！")
    
    

# 生成pdf
def pdfBulid(ui, pdf_pages, save_path, doc_type, flag_enhance):
    pdf_list = [] 
    # 获取图片尺寸
    image_w, image_h = getImageSize(pdf_pages[0])

    # 根据类型选纸张
    if doc_type == 'pdf':
        if A4_w / image_w < A4_h / image_h:
            k = A4_w / image_w
        else:
            k = A4_h / image_h
            pagesize = A4
    elif doc_type == 'ppt':
        pagesize = A3
        
    # PDF 模板
    PDF = SimpleDocTemplate(save_path, 
                            pagesize=pagesize, 
                            rightMargin=72, 
                            leftMargin=72, 
                            topMargin=72, 
                            bottomMargin=18,
    )

    # 遍历每一页pdf
    for num, page in enumerate(pdf_pages, start=1):
        if flag_enhance:
            # 图像处理
            if doc_type == 'ppt':
                image_roate(page) # 旋转
                image_enhance(page) # 增强
                ui.printlog('PPT 第 %d 张图片处理成功！'%num)
            elif doc_type == 'pdf':
                image_enhance(page) # 增强
                ui.printlog('PDF 第 %d 张图片处理成功！'%num)
            
        if doc_type == 'ppt':
            data = Image(page, image_w, image_h)     # ppt
        elif doc_type == 'pdf':
            data = Image(page, image_w*k, image_h*k) # pdf
        
        # 添加图片
        pdf_list.append(data)
        pdf_list.append(PageBreak())
    

    try:
        # 生成PDF
        ui.printlog("生成PDF...")
        PDF.build(pdf_list)
        ui.printlog("PDF 转换成功")
    except Exception as err:
        ui.printlog("PDF生成错误: " + err)

if __name__ == '__main__':
    path = './img'
    #image2PDF(path,'./img/out.pdf','pdf')
